import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { RootState } from "./store";
import { NulResponse, createEmptyRequest, createRequest } from "./common";
import { cloneArray } from "../util/Arrays";
import { getRequest } from "../util/Auth";

interface CustomerEntry {
  id: number;
  name: string;
  type: string;
  phone: string;
  address: string;
  notes: string;
}

interface CustomerState {
  fetched: boolean;
  entries: CustomerEntry[];
}

const customerInitialState: CustomerState = {
  fetched: false,
  entries: []
};

interface CustomerRequest {
  name: string;
  type: string;
  phone: string;
  address: string;
  notes: string;
}

interface CreateCustomerResponse {
  id: number;
}

interface CustomerDeleteRequest {
  id: number[];
}


export const fetchAllCustomerEntries = createAsyncThunk('api/fetchAllCustomerEntries', async (_, { getState, rejectWithValue }) => {
  const state = getState() as RootState;
  try {
    const request = getRequest(state);
    const response = await request.post<NulResponse<CustomerEntry[]>>('/service/customer/fetchAll',
      createEmptyRequest());
    return response.data;
  }
  catch (e) {
    return rejectWithValue(e);
  }
});

export const createNewCustomer = createAsyncThunk('api/createCustomer', async (customer: CustomerRequest, { getState, rejectWithValue }) => {
  const state = getState() as RootState;
  try {
    const request = getRequest(state);
    const response = await request.post<NulResponse<CreateCustomerResponse>>('/service/customer/createEntry',
      createRequest(customer));
    return response.data;
  }
  catch (e) {
    return rejectWithValue(e);
  }
});

export const modifyCustomer = createAsyncThunk('api/modifyCustomer', async (customer: CustomerEntry, { getState, rejectWithValue }) => {
  const state = getState() as RootState;
  try {
    const request = getRequest(state);
    const response = await request.post<NulResponse<null>>('/service/customer/modifyEntry', createRequest(customer));
    return response.data;
  }
  catch (e) {
    return rejectWithValue(e);
  }
});

export const deleteCustomer = createAsyncThunk('api/deleteCustomer', async (id: number[], { getState, rejectWithValue }) => {
  const state = getState() as RootState;
  try {
    const request = getRequest(state);
    const response = await request.post<NulResponse<null>>('http://localhost:8080/service/customer/deleteEntry',
      createRequest<CustomerDeleteRequest>({ id }));
    return response.data;
  }
  catch (e) {
    return rejectWithValue(e);
  }
});

const customerSlice = createSlice({
  name: 'customer',
  initialState: customerInitialState,
  reducers: {

  },
  extraReducers: (builder) => {
    builder.addCase(fetchAllCustomerEntries.rejected, (state, action) => {
      console.error(action.error);
    }).addCase(fetchAllCustomerEntries.fulfilled, (state, action) => {
      state.fetched = true;
      state.entries = action.payload.result;
    }).addCase(createNewCustomer.fulfilled, (state, action) => {
      const entry: CustomerEntry = {
        ...action.meta.arg,
        ...action.payload.result
      };
      state.entries.push(entry);
      state.entries.sort((a, b) => a.id - b.id);
    }).addCase(createNewCustomer.rejected, (state, action) => {
      console.error(action.error);
    }).addCase(modifyCustomer.rejected, (state, action) => {
      console.error(action.error);
    }).addCase(modifyCustomer.fulfilled, (state, action) => {
      const index: number = state.entries.findIndex(item => item.id === action.meta.arg.id);
      if (index !== -1) {
        state.entries[index] = action.meta.arg;
      }
    }).addCase(deleteCustomer.rejected, (state, action) => {
      console.error(action.error);
    }).addCase(deleteCustomer.fulfilled, (state, action) => {
      const deletedIds: number[] = cloneArray(action.meta.arg);
      const customerEntries: CustomerEntry[] = state.entries;
      deletedIds.sort();
      const result: CustomerEntry[] = [];
      for (let i = 0, j = 0; j < customerEntries.length; ++j) {
        if (customerEntries[j].id !== deletedIds[i])
          result.push(customerEntries[j]);
        else ++i;
      }
      state.entries = result;
    })
  }


});

export type { CustomerEntry };
export const { actions } = customerSlice;
export const selectCustomerEntries = (state: RootState) => state.customerInformationReducer.entries;
export const selectCustomerFetched = (state: RootState) => state.customerInformationReducer.fetched;
export default customerSlice.reducer;